package com.wiwf.model.manage.socket;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections4.map.HashedMap;
import org.springframework.util.ObjectUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.fastmybatis.core.query.Query;
import com.wiwf.model.bean.SysUserVoto;
import com.wiwf.model.mapper.admin.bean.SysMsgEntity;
import com.wiwf.model.mapper.admin.dao.SysMsgMapper;
import com.wiwf.model.security.service.SysTokenService;

public class BaseWebSocketDispatcher extends TextWebSocketHandler {
	
	private SysTokenService tokenService;
	
	private SysMsgMapper sysMsgMapper;
	
	private WebSocketSession session;
	
	public BaseWebSocketDispatcher(SysTokenService tokenService, SysMsgMapper sysMsgMapper) {
		this.tokenService = tokenService;
		this.sysMsgMapper = sysMsgMapper;
	}
	
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        this.session = session;
    }
    
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		String strMsg = message.getPayload();
		if(! session.isOpen()) {
			return;
		}
		// 接受私信
		if(strMsg.equalsIgnoreCase("accept")) {
			SysUserVoto sysUser = getUserInfo();
			if(ObjectUtils.isEmpty(sysUser)) {
				session.sendMessage(new TextMessage("{\"code\":\"401\", \"msg\": \"无权限访问\"}"));
			} else {
				Integer userId = sysUser.getUserId();
				
				Query query = new Query().eq("user_take_id", userId).eq("is_read", 0).addSort("time");
				SysMsgEntity msgObj = sysMsgMapper.getByQuery(query);
				if(ObjectUtils.isEmpty(msgObj)) {
					session.sendMessage(new TextMessage("{\"code\":\"401\", \"msg\": \"无权限访问\"}"));
					return;
				}
				HashedMap<String, Object> msgData = new HashedMap<String, Object>();
				msgData.put("userName", msgObj.getUserName());
				msgData.put("msg", msgObj.getMsg());
				msgData.put("msgId", msgObj.getMsgId());
				msgData.put("code", 200);
				
				session.sendMessage(new TextMessage(JSONObject.toJSONString(msgData)));
				msgObj.setIsRead(1);
				sysMsgMapper.update(msgObj);
			}
			return;
		}
		// 接受通告
		if(strMsg.equalsIgnoreCase("notice")) {
			Query query = new Query().eq("type", 0).addSort("time");
			List<SysMsgEntity> listData = sysMsgMapper.list(query);
			session.sendMessage(new TextMessage(JSONArray.toJSONString(listData)));
			return;
		}
		
		if(strMsg.indexOf(",")> 0) {
			String[] StrMsgs = strMsg.split(",");
			String key = StrMsgs[0];
			String data = StrMsgs[1];
			Integer type = 0;
			Integer userTakeId = 0;
			if(StrMsgs.length == 4) {
				type = Integer.parseInt(StrMsgs[2]);
				userTakeId = Integer.parseInt(StrMsgs[3]);
			}
			
			if(key.equalsIgnoreCase("login")) {
				// 授权
				SysUserVoto sysUser = tokenService.getTokenUser(data);
				if(ObjectUtils.isEmpty(sysUser)) {
					session.sendMessage(new TextMessage("{\"code\":\"401\", \"msg\": \"无权限访问\"}"));
				} else {
					setUserInfo(sysUser);
					session.sendMessage(new TextMessage("{\"code\":\"200\", \"data\": "+ JSONObject.toJSONString(sysUser) +"}"));
				}
			} else if(key.equalsIgnoreCase("send")) {
				// 授权后发送信息
				SysUserVoto sysUser = getUserInfo();
				if(ObjectUtils.isEmpty(sysUser)) {
					session.sendMessage(new TextMessage("{\"code\":\"401\", \"msg\": \"无权限访问\"}"));
				} else {
					SysMsgEntity sysMsg = new SysMsgEntity(sysUser.getUserId(), type, data, new Date());
					sysMsg.setUserName(sysUser.getName());
					if(type.equals(1)) {
						sysMsg.setUserTakeId(userTakeId);
					}
					sysMsgMapper.save(sysMsg);
					
					session.sendMessage(new TextMessage("{\"code\":\"200\", \"msg\": \"ok\"}"));
				}
			}
		} else {
			session.sendMessage(new TextMessage("{\"code\":\"401\", \"msg\": \"异常信息\"}"));
		}
	}
	
	private final String userInfoKey = "userInfo";
	
	private void setUserInfo(SysUserVoto sysUser) {
		sysUser.setMenus(null);
		session.getAttributes().put(userInfoKey, sysUser);
	}
	
	private SysUserVoto getUserInfo() {
		return (SysUserVoto) session.getAttributes().get(userInfoKey);
	}
	
	
}
